<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { auth, info } from '@/api/user'
import { upload } from '@/api/file'
import type { StudentInfo } from '@/api/user/type'
import { AuthStatus } from './common'
import { toast } from '@/utils/common'
import { BaseResponse } from '@/api/base'
import { baseUrl } from '@/config'

const formData = ref<StudentInfo>({
  id: 0,
  name: '',
  studentNo: '',
  college: '',
  major: '',
  classes: '',
  picArr: [],
  pic: '',
  status: 0,
  statusDesc: '未认证'
})
const formRef = ref()
const formRules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: ['blur'] },
    { min: 2, max: 10, message: '姓名长度为2-10个字符' }
  ],
  studentNo: [
    { required: true, message: '请输入学号', trigger: ['blur'] },
    { pattern: /^\d{10}$/, message: '学号应为10位数字' }
  ],
  college: [
    { required: true, message: '请输入学院名称', trigger: ['blur'] }
  ],
  major: [
    { required: true, message: '请输入专业名称', trigger: ['blur'] }
  ],
  classes: [
    { required: true, message: '请输入班级', trigger: ['blur'] }
  ],
  picArr: [
    {
      validator: (rule: any, value: string[]) => {
        return value && value.length >= 2
      },
      message: '请上传学生证正反面照片',
      trigger: ['change']
    }
  ]
})

onLoad(async () => {
  const res = await info()
  if (!res.data) return
  formData.value = res.data
  formData.value.picArr = res.data.pic.split(',').map((item: string) => {
    return {
      url: baseUrl + item,
      name: 'file',
      status: 'success',
      message: ''
    }
  })
  formData.value.statusDesc = AuthStatus[res.data.status]
})

const afterRead = (e: any) => {
  try {
    let fileList = [].concat(e.file)
    let fileListLen = formData.value.picArr.length
    fileList.map((item: any) => {
      formData.value.picArr.push({
        ...item,
        status: 'uploading',
        message: '上传中'
      });
    })
    fileList.forEach(async (file: any) => {
      const res: BaseResponse = await upload(file.url, file.name)
      let item = formData.value.picArr[fileListLen];
      formData.value.picArr.splice(
        fileListLen,
        1,
        Object.assign(item, {
          status: 'success',
          message: '',
          url: res.data.actionUrl
        })
      )
      fileListLen++
    })
  } catch (e) {
    toast('上传失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 先进行表单验证
    const valid = await formRef.value?.validate()
    if (!valid) return

    // 检查图片数量
    if (formData.value.picArr.length < 2) {
      return toast('请上传学生证正反面照片')
    }
    formData.value.pic = formData.value.picArr.map((item: any) => item.url.substring(item.url.indexOf('files') - 1)).join(',')
    const res: BaseResponse = await auth(formData.value)
    uni.showToast({
      title: res.tips,
      success: () => {
        setTimeout(() => {
          uni.navigateBack()
          uni.emit('backRefresh')
        }, 500)
      }
    })
  } catch (error) {
    toast(error.tips)
  }
}
</script>

<template>
  <view class="student">
    <uv-form class="form-container" ref="formRef" :model="formData" labelWidth="100" :rules="formRules">
      <uv-form-item label="姓名" prop="name" borderBottom>
        <uv-input v-model="formData.name" border="none" placeholder="请输入真实姓名" />
      </uv-form-item>

      <uv-form-item label="学号" prop="studentNo" borderBottom>
        <uv-input v-model="formData.studentNo" border="none" placeholder="请输入学号" />
      </uv-form-item>

      <uv-form-item label="学院" prop="college" borderBottom>
        <uv-input v-model="formData.college" border="none" placeholder="请输入学院名称" />
      </uv-form-item>

      <uv-form-item label="专业" prop="major" borderBottom>
        <uv-input v-model="formData.major" border="none" placeholder="请输入专业名称" />
      </uv-form-item>

      <uv-form-item label="班级" prop="classes" borderBottom>
        <uv-input v-model="formData.classes" border="none" placeholder="例: 2023级1班" />
      </uv-form-item>

      <uv-form-item label="学生证照片" prop="picArr" borderBottom labelPosition="top">
        <view class="upload-container">
          <uv-upload v-model="formData.picArr" :file-list="formData.picArr" :max-count="2" :deletable="true"
            @afterRead="afterRead" @delete="(event: any) => formData.picArr.splice(event.index, 1)"
            upload-text="上传学生证正反面" width="120" height="120" />
        </view>
      </uv-form-item>
    </uv-form>

    <uv-button type="primary" color="#ff7744" text="提交认证" class="submit-btn" @click="handleSubmit" />
  </view>
</template>

<style lang="scss" scoped>
.student {
  padding: 20rpx;

  .form-container {
    background: #fff;
    border-radius: 12rpx;
    padding: 0 20rpx;

    ::v-deep .uv-form-item__body__right__content__slot {
      justify-content: flex-end;
    }
  }

  .upload-container {
    display: flex;
    gap: 20rpx;
    flex-wrap: wrap;
    padding: 20rpx 0;

    .upload-avatar {
      border: 2rpx dashed #eee;
    }
  }

  .submit-btn {
    margin-top: 40rpx;
  }
}
</style>
